# -*- coding: utf-8 -*-
import os
import threading
from flask import (
    render_template, redirect, session, request, jsonify,make_response, url_for
    )
from . import main
from ..funcs import (
    FuzzyQuery, Book, db, to_dict, get_recommend, get_type, iscollect, start_spider, reptile
    )


qu = FuzzyQuery()

# 每个请求来了之后都会经此验证是否登录
@main.before_request
def before_user():
    if 'user_id' in session:
        return
    else:
        return redirect('/login')
        return


@main.route('/')
def index():
    # 获取推荐书籍
    books = get_recommend('www.booktxt.com')
    result = {
        'title' : '经典推荐',
        'books' : to_dict(books)
    }
    return render_template('/main/index.html', result=result)

@main.route('/search', methods=['GET', 'POST'])
def search():
    '''搜索指定关键词的路由'''

    # 得到搜索词汇
    keyword = request.values.get('keyword')
    

    # 根据空格拆分多个关键词
    keywords = keyword.split()
    # 调用方法在数据库中查询出相关数据
    
    res = qu.querys(keywords)
    title = '搜索结果'

    if res == None or len(res) <= 0:
        # res = db.query(Book, {'name':'败天神皇'})
        title = '没有搜索到数据'
        res = []

    books = to_dict(res)
    # 将搜索记录添加到session
    if 'searchs' in session:
        # 判断有没有搜索过
        searchs = session['searchs'].split(',')
        for kw in searchs:
            if kw == keyword:
                # 如果在里面就把原来的删掉，把新的添加到最后
                searchs.remove(kw)
        searchs.append(keyword)
        session['searchs'] = str(','.join(searchs))
    else:
        session['searchs'] = keyword
        
    result = {
        'title' : title,
        'books' : books,
        'searchs' : session['searchs'].split(',')
    }
    return jsonify(result)

@main.route('/book/<id>')
def book(id):
    # 根据id得到书籍信息
    res = db.query(Book, {'Id': id}, True)
    # 查看书籍是否收藏
    isct = iscollect(int(session['user_id']), id)

    # 得到书籍的具体内容
    # 判断站点
    url = res.showUrl
    if 'booktxt' in url:
        # www.booktxt.net
        rept = reptile.Booktxt()
        book = rept.getbook(res.showUrl)
        book['type'] = res.booktype
        book['id'] = id
        book['isct'] = isct

    return render_template('/main/book.html', book=book)

@main.route('/read/<id>/<sec>')
def read(id, sec):
    '''阅读具体章节'''
    
    # 根据id得到书籍信息
    res = db.query(Book, {'Id': id}, True)
    # 判断站点
    url = res.showUrl
    contents = {}
    if 'booktxt' in url:
        # 得到章节内容
        rept = reptile.Booktxt()
        contents = rept.get_sec_content(res.Id, url+sec)
    return render_template('main/read.html', contents=contents)

@main.route('/morebook')
def morebook():
    # 当书籍过多是，调用此路由显示多数书籍
    bt = request.values.get('tp')
    result = {
        'title' : bt,
        'books' : []
    }
    if bool(bt):
        res = get_type(bt)
        result['books'] = to_dict(res)
    return render_template('main/more_book.html', result=result)


@main.route('/down/<book_id>')
def down(book_id):
    '''下载书籍'''
    res = db.query(Book, {'Id': book_id}, True)

    rept = reptile.Booktxt()
    name, content = rept.down_book(res.showUrl)
    response = make_response(content)
    response.headers["Content-Disposition"] = 'attachment; filename="{0}".txt'.format(name.encode().decode('latin-1'))
    return response
    
@main.route('/collect', methods=['GET', 'POST'])
def collect():

    if request.method == 'POST':
        # 将书籍加入用户藏书
        user_id = session['user_id']
        book_id = request.values.get('id')
        # 修改用户藏书
        res = iscollect(int(user_id), book_id, True)
        state = '收藏'
        if res:
            state = '已收藏'
        result = {
            'state' : state
        }
        return jsonify(result)
@main.route('/help')
def help():
    return render_template('main/help.html')

@main.route('/about')
def about():
    return render_template('main/about.html')


@main.route('/spider', methods=['GET', 'POST'])
def spider():
    '''启动爬取的方法'''
    # print('=' * 20, '静茹爬虫')
    # 得到爬虫对象
    url = request.values.get('url')

    isok = start_spider(url)
    return jsonify({'result': isok})